from django.shortcuts import render
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework_jwt.settings import api_settings
from oauth.models import OAuthQQUser
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from oauth.serializers import QQAuthUserSerializer


class QQAuthURLView(APIView):
    """
    获得ＱＱ的登陆界面或登陆二维码
    目的：返回登陆ｑｑ的url
    1 根据第三方提供的方法获得ｕｒｌ（及ｏｐｅｎｉｄ）
    """
    def get(self,request):
        """
        待核实目的
        :param request:
        :return:
        """
        # 待核实目的
        state = request.query_params.get("state",None)
        if state is None:
            state = '/'
        # 获取ｑｑ登陆页面的，先获得操作第三方的实例对象，并且指定成功登陆ｕｒｌ后页面将跳转的前端需求的具体路径state
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        # 获取QQ登录扫码页面，扫码后得到Authorization Code
        login_url = oauth.get_qq_url()
        # access_token = oauth.get_access_token(code)
        # openid = oauth.get_open_id(access_token)
        return Response({"login_url": login_url})


class QQAuthUserView(CreateAPIView):
    # 用于绑定ＱＱ新用户，指定序列化器
    serializer_class = QQAuthUserSerializer
    """
    用户扫码登录的回调处理
    用户登录。用户登录成功。qq服务器会引导用户跳转回美多商城页面
    在跳转的美多商城的连接中qq会写如一个code数据
    前端回提取连接中的code数据
    前端发送ajax请求携带code数据到后端
    后端拿到code请求qq获取access_token
    通过access_token请求qq获取openid
    判断openid是否和美多商城用户进行过绑定
    如果已经绑定过直接登录成功
    没有绑定过，进到绑定页面进行绑定

    """

    def get(self,request):
        code = request.query_params.get("code", None)
        print(code)
        if code is None:
            return Response({"mssage":"没有code值"},status=400)
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state="/")
        try:
            access_token = oauth.get_access_token(code)
            print(code)
        except Exception as e:
            # print(e)
            return Response({'errors': e}, status=400)

        try:
            openid = oauth.get_open_id(access_token)
        except:
            return Response({'errors': 'qq服务器异常'}, status=400)
        #判断openid是否和美多商城用户进行过绑定
        try:
            # qq_oauth = OAuthQQUser.objects.get(openid=openid)
            # 不能使用filter查询，获得的为一个列表
            qq_oauth = OAuthQQUser.objects.filter(openid=openid)
            qq_oauth = qq_oauth[0]

        except:
            # 没有绑定过，进到绑定页面进行绑定
            # 使用加密工具,先获得加密工具tjs，并指定加密秘钥settings.SECRET_KEY和有效时间300
            tjs = TJS(settings.SECRET_KEY, 300)
            # 对openid进行加密,dumps(加密数据必须为json数据)
            openid_token = tjs.dumps({'openid': openid}).decode()
            return Response({'access_token': openid_token})
        else:

            # 如果已经绑定过直接登录成功
            # 获取用户对像
            user = qq_oauth.user

            # 生成token值
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

        return Response(
            {
                'token': token,
                'user_id': user.id,
                'username': user.username,

            }
        )
